//
//  WXPInputNewCardInfoVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/3/11.
//
//

#import "WXPInputNewCardInfoVC.h"
#import "WXPAuthBankCardHeaderView.h"
#import "WXPAuthSelectView.h"
#import "WXPAuthBankCardFooterView.h"
#import "WXPInputNewCardGetCodeView.h"

@interface WXPInputNewCardInfoVC ()<UITextFieldDelegate>

@property (nonatomic, strong) WXPNavView * navView;

@property (nonatomic, strong) UIView * headerView;
@property (nonatomic, strong) WXPAuthBankCardHeaderView * viewHeader;
@property (nonatomic, strong) UIView * viewBankCardTips;
@property (nonatomic, strong) UIView * viewVerifyBankCard;
@property (nonatomic, strong) WXPAuthSelectView * tfVerifyBankCard;
@property (nonatomic, strong) WXPAuthBankCardFooterView * viewFooter;
@property (nonatomic, strong) UIView * viewBtnBack;
@property (nonatomic, strong) UIButton * btnSubmit;

@property (nonatomic, strong) WXPCommonAgreementView * agreementView;
@property (nonatomic, assign) BOOL bankCardSuccess;
@property (nonatomic, assign) BOOL verifyBankCardSuccess;

@property (nonatomic, strong) WXPInputNewCardGetCodeView * getCodeView;

@end

@implementation WXPInputNewCardInfoVC

#pragma mark - lazy
- (WXPNavView *)navView{
    if (_navView == nil) {
        _navView = [WXPNavView  new];
        [_navView resetViewWithTitle:@"Modificar su cuenta bancaria"];
        _navView.leftTop = XY(0, 0);
        _navView.blockPop = ^{
            [Global_Nav popToClass:@"WXPBankCardVC"];
        };
    }
    return  _navView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [UIView new];
    }
    return _headerView;
}
- (WXPCommonAgreementView *)agreementView{
    if (!_agreementView) {
        _agreementView = [WXPCommonAgreementView new];
        _agreementView.centerXBottom = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT-LEFT_MARDIN);
    }
    return _agreementView;
}
- (WXPAuthBankCardHeaderView *)viewHeader{
    if (!_viewHeader) {
        _viewHeader = [[WXPAuthBankCardHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-LEFT_MARDIN*2, 0)];
        _viewHeader.type = 2;
        WEAKSELF
        _viewHeader.tfBankCard.blockTextFieldDidChange = ^{
            [weakSelf verifyBankCard];
            [weakSelf verifyConfirmarBankCard];
        };
        _viewHeader.blockResetAuthBtn = ^{
            [weakSelf resetAuthBtn];
        };
    }
    return _viewHeader;
}
- (UIView *)viewBankCardTips
{
    if (_viewBankCardTips == nil) {
        _viewBankCardTips = [UIView  new];
        _viewBankCardTips.widthHeight = XY(self.tableView.width, 0);
        _viewBankCardTips.backgroundColor = [UIColor clearColor];
        UIView * view = [UIView new];
        view.backgroundColor = COLOR_WHITE;
        view.width = _viewBankCardTips.width;
        [_viewBankCardTips addSubview:view];
        UILabel * titleLabel = [UILabel new];
        titleLabel.fontNum = 12;
        titleLabel.textColor = COLOR_RED;
        titleLabel.numberOfLines = 0;
        titleLabel.lineSpace = 3;
        [titleLabel fitTitle:@"Por favor, ingrese su número CLABE INTERBANCARIA tal como aparece en su Estado de Cuenta, asegurándose de que conste de 18 dígitos. O proporcione su número de tarjeta bancaria tal como aparece en su tarjeta, asegurándose de que conste de 16 dígitos" variable:SCREEN_WIDTH-4*LEFT_MARDIN];
        titleLabel.leftTop = XY(LEFT_MARDIN, Ratio(12));
        [view addSubview:titleLabel];
        view.height = titleLabel.bottom;
        view.centerXTop = XY(_viewBankCardTips.width/2, 0);
        _viewBankCardTips.height = view.bottom;
    }
    return  _viewBankCardTips;
}
// 确认银行卡号
- (UIView *)viewVerifyBankCard{
    if (!_viewVerifyBankCard) {
        _viewVerifyBankCard = [UIView new];
        _viewVerifyBankCard.width = self.tableView.width;
        UIView * view = [UIView new];
        view.backgroundColor = COLOR_WHITE;
        view.width = self.tableView.width;
        [_viewVerifyBankCard addSubview:view];
        [view addSubview:self.tfVerifyBankCard];
        self.tfVerifyBankCard.leftTop = XY(0, 0);
        view.height = self.tfVerifyBankCard.bottom;
        view.centerXTop = XY(_viewVerifyBankCard.width/2, 0);
        _viewVerifyBankCard.height = view.bottom;
    }
    return _viewVerifyBankCard;
}
- (WXPAuthSelectView *)tfVerifyBankCard
{
    if (_tfVerifyBankCard == nil) {
        _tfVerifyBankCard = [WXPAuthSelectView  new];
        _tfVerifyBankCard.tag = 1;
        _tfVerifyBankCard.tfContent.keyboardType = UIKeyboardTypeNumberPad;
        _tfVerifyBankCard.tfContent.font = [UIFont systemFontOfSize:14];
        _tfVerifyBankCard.imageArrow.hidden = true;
        _tfVerifyBankCard.tfContent.userInteractionEnabled = true;
        ModelBtn * model = [ModelBtn new];
        model.title = @"Verificar la cuenta CLABE o tarjeta bancaria";
        model.content = @"Por favor escribe";
        [_tfVerifyBankCard resetViewWithModel:model];
        _tfVerifyBankCard.tfContent.delegate = self;
        WEAKSELF
        _tfVerifyBankCard.blockTextFieldDidChange = ^{
            [weakSelf verifyBankCard];
            [weakSelf verifyConfirmarBankCard];
        };
        //        _tfVerifyBankCard.blockTextFieldDidChange = ^(BOOL isInput) {
        //            [weakSelf verifyBankCard];
        //            [weakSelf verifyConfirmarBankCard];
        //
        //            // 这个类里面两个LRBMailTextField，没法直接用isInput区分了
        ////            if(isInput){
        ////                [GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_INPUT type:KEY_input];
        ////            }
        //            // 区分是输入
        //            static NSUInteger previousLength = 0;
        //            NSUInteger currentLength = weakSelf.tfVerifyBankCard.contentTextField.text.length;
        ////            if (currentLength > previousLength || isInput) {
        //            if (isInput) {
        //                [GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_INPUT type:KEY_input];
        //            }
        //            previousLength = currentLength;
        //
        //
        //
        //            [weakSelf.tfVerifyBankCard.contentTextField becomeFirstResponder];
        //        };
               
        //        _tfVerifyBankCard.blockTextFieldDidEndEditing = ^{
        //            [GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_LOST_FOCUS type:KEY_input];
        //        };
        //        _tfVerifyBankCard.blockCharactersInRange = ^{
        //            [GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_PARSE type:KEY_input];
        //        };
    }
    return  _tfVerifyBankCard;
}
- (WXPAuthBankCardFooterView *)viewFooter{
    if (!_viewFooter) {
        _viewFooter = [[WXPAuthBankCardFooterView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-2*LEFT_MARDIN, 0)];
    }
    return _viewFooter;
}
- (UIView *)viewBtnBack{
    if (!_viewBtnBack) {
        _viewBtnBack = [UIView new];
        _viewBtnBack.backgroundColor = [UIColor clearColor];
        _viewBtnBack.width = self.tableView.width;
        _viewBtnBack.height = self.btnSubmit.height;
        _viewBtnBack.userInteractionEnabled = true;
        self.btnSubmit.centerXTop = XY(_viewBtnBack.width/2, 0);
        [_viewBtnBack addSubview:self.btnSubmit];
    }
    return _viewBtnBack;
}
- (UIButton *)btnSubmit{
    if (_btnSubmit == nil) {
        _btnSubmit = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnSubmit.backgroundColor = COLOR_PRIMARY;
        [_btnSubmit setTitleColor:COLOR_BLACK forState:UIControlStateNormal];
        _btnSubmit.titleLabel.font = [UIFont systemFontOfSize:14];
        _btnSubmit.widthHeight = XY(SCREEN_WIDTH-LEFT_MARDIN*4, BUTTON_HEIGHT);
        _btnSubmit.userInteractionEnabled = false;
        _btnSubmit.alpha = 0.5;
        [GlobalMethod setRoundView:_btnSubmit color:[UIColor clearColor] numRound:BUTTON_HEIGHT/2 width:0];
        [_btnSubmit setTitle:@"Enviar" forState:(UIControlStateNormal)];
        WEAKSELF
        [_btnSubmit setNoRepeatActionWithInterval:3 action:^(UIButton * _Nonnull button) {
            // 打点
            [GlobalMethod hitPointWithPageName:KEY_EditBankcard action:KEY_Click extInfo:nil];
            [NSObject clickFeedback];
            [weakSelf.btnSubmit addClickAnimate];
            [weakSelf.view endEditing:true];
            [weakSelf requestSendSms];
            [weakSelf.getCodeView resetViewAndTimer];
            [weakSelf.view addSubview:weakSelf.getCodeView];
        }];
    }
    return _btnSubmit;
}
- (WXPInputNewCardGetCodeView *)getCodeView
{
    if (_getCodeView == nil) {
        _getCodeView = [WXPInputNewCardGetCodeView  new];
        WEAKSELF
        _getCodeView.blockSendSmsClick = ^{
            [weakSelf requestSendSms];
        };
        _getCodeView.blockEnviarClick = ^{
            [weakSelf requestModifyBankCard];
        };
    }
    return  _getCodeView;
}

#pragma mark - viewDidLoad
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_EditBankcard action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    self.bankCardSuccess = true;
    self.verifyBankCardSuccess = true;
    
    UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [self.view addGestureRecognizer:tapGestureRecognizer];
    
    [self configUI];
    [self requestBankList];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

- (void)configUI{
    self.view.backgroundColor = COLOR_BACKGROUND;
    self.viewBG.backgroundColor = COLOR_BACKGROUND;
    self.tableHeaderTopBg.backgroundColor = [UIColor clearColor];
    self.tableView.backgroundColor = COLOR_WHITE;
    
    self.tableView.height = self.agreementView.top-10-self.navView.bottom-10;
    self.tableView.width = SCREEN_WIDTH-2*LEFT_MARDIN;
    [GlobalMethod setRoundView:self.tableView color:COLOR_WHITE numRound:16 width:0];
    self.tableView.centerXTop = XY(SCREEN_WIDTH/2, self.navView.bottom+10);
    
    
    [self.view addSubview:self.navView];
    [self.view addSubview:self.agreementView];
    
    
    [self resetHeaderView];
    [self resetFooterView];
    WEAKSELF
//    [self.btnAuth setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
//        [NSObject clickFeedback];
//        [weakSelf.btnAuth addClickAnimate];
//        [weakSelf requestSubmitAuth];
//    }];
    
    
//    self.tableView.height = self.agreementView.top-10-self.navView.bottom-10;
//    self.tableView.width = SCREEN_WIDTH-2*LEFT_MARDIN;
//    [GlobalMethod setRoundView:self.tableView color:COLOR_WHITE numRound:16 width:0];
//    self.tableView.centerXTop = XY(SCREEN_WIDTH/2, self.navView.bottom+10);
    
}

#pragma mark - resetHeaderView
- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        self.viewHeader,
    ]];
    self.tableView.tableHeaderView = self.headerView;
}

- (void)resetFooterView{
    [self.viewFooter resetVerifyBankCardIsShowTips:!self.verifyBankCardSuccess];
    UIView * viewMark = [UIView initWithViews:@[
        self.viewFooter,
        [GlobalMethod getViewWithHeight:80],
        self.viewBtnBack,
    ]];
    self.tableView.tableFooterView = viewMark;
}

// 验证 银行卡号
- (void)verifyBankCard{
    BOOL change = false;
    BOOL result = (self.viewHeader.tfBankCard.tfContent.text.length == 16 || self.viewHeader.tfBankCard.tfContent.text.length == 18);
    result = isStr(self.viewHeader.tfBankCard.tfContent.text)?result:true;
    change = self.bankCardSuccess==result?false:true;
    self.bankCardSuccess = result;
    if(change){
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
// 验证 确认银行卡号
- (void)verifyConfirmarBankCard{
    BOOL change = false;
    BOOL result = (self.tfVerifyBankCard.tfContent.text.length == 16 || self.tfVerifyBankCard.tfContent.text.length == 18);
    result = ([self.viewHeader.tfBankCard.tfContent.text isEqualToString:self.tfVerifyBankCard.tfContent.text])?true:false;
    result = isStr(self.tfVerifyBankCard.tfContent.text)?result:true;
    change = self.verifyBankCardSuccess==result?false:true;
    self.verifyBankCardSuccess = result;
    if(change){
        [self resetFooterView];
    }
    [self resetAuthBtn];
}

// 认证按钮更新
- (void)resetAuthBtn{
    if(self.bankCardSuccess &&
       self.verifyBankCardSuccess &&
       isStr(self.viewHeader.tfBankCard.tfContent.text) &&
       isStr(self.tfVerifyBankCard.tfContent.text) &&
       isStr(self.viewHeader.bankNameView.tfContent.text)){
        self.btnSubmit.userInteractionEnabled = true;
        self.btnSubmit.alpha = 1;
    }else{
        self.btnSubmit.userInteractionEnabled = false;
        self.btnSubmit.alpha = 0.5;
    }
}

#pragma mark -  键盘
// 键盘收起时执行操作
- (void)keyboardWillHide:(NSNotification *)notification {
    self.viewHeader.pickerView.bottom = SCREEN_HEIGHT;
    self.getCodeView.backView.bottom = SCREEN_HEIGHT;
}
- (void)keyboardWillShow:(NSNotification *)notification {
    self.viewHeader.pickerView.bottom = SCREEN_HEIGHT-self.viewHeader.pickerView.viewBack.height+Ratio(26);
    self.getCodeView.backView.bottom = SCREEN_HEIGHT-Ratio(190);
}
// 获得焦点
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [GlobalMethod hitPointWithPageName:KEY_EditBankcard action:KEY_CLABE2_Focus extInfo:nil];
    //[GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_GET_FOCUS type:KEY_input];
}


#pragma mark - 手势点击
- (void)tapClick:(UITapGestureRecognizer * )tap{
    [self.view endEditing:true];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0){
        // 银行卡号错误提示
        return self.bankCardSuccess?[UIView new]:self.viewBankCardTips;
    }else{
        // 验证银行卡号
        return self.viewVerifyBankCard;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return self.bankCardSuccess?CGFLOAT_MIN:self.viewBankCardTips.height;
    }else{
        return self.viewVerifyBankCard.height;
    }
}
//table footer
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


#pragma mark - request
// 银行列表
- (void)requestBankList{
    [RequestApi requestBankListWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        self.viewHeader.bankNameAry = [response arrayValueForKey:KEY_banks];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 发送短信验证码
- (void)requestSendSms{
    [GlobalMethod hitPointWithPageName:KEY_EditBankcard action:KEY_Send_Sms_Click extInfo:@{@"phone": [GlobalData sharedInstance].Global_ModelUser.phone}];
    [RequestApi requestSendSmsWithPhone:[GlobalData sharedInstance].Global_ModelUser.phone type:KEY_modify_bank smsChannel:KEY_SMS delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {

        // 验证码发送成功
        [GlobalMethod hitPointWithPageName:KEY_EditBankcard action:KEY_Send_Sms_End extInfo:@{@"isSuccess": @"true", @"errorMsg": @""}];
        // [GlobalMethod showAlert:@"Código de verificación por SMS obtenido con éxito"];
        self.getCodeView.codigoBtn.hidden = true;
        self.getCodeView.timeLabel.hidden = false;
        [self.getCodeView startCountdown];

    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [GlobalMethod hitPointWithPageName:KEY_EditBankcard action:KEY_Send_Sms_End extInfo:@{@"isSuccess": @"false", @"errorMsg": errorStr}];
    }];
}

// 修改银行卡
- (void)requestModifyBankCard{
    [GlobalMethod hitPointWithPageName:KEY_EditBankcard action:KEY_Save_Start extInfo:nil];
    [RequestApi requestModifyBankCardWithVcode:self.getCodeView.verificacionTextField.text step:self.modelBankCard.step bankCode:self.viewHeader.bankCode bankCard:self.viewHeader.tfBankCard.tfContent.text bankName:self.viewHeader.bankNameView.tfContent.text delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        [GlobalMethod hitPointWithPageName:KEY_EditBankcard action:KEY_Save extInfo:nil];
        [GlobalMethod showAlert:@"Su cuenta bancaria fue\nmodificada con éxito!"];
        [[NSNotificationCenter defaultCenter] postNotificationName:JUMP_TO_HOMEPAGE object:nil userInfo:nil];
        [Global_Nav popToRootViewControllerAnimated:true];

    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
        [self.getCodeView resetErrorLabelWithErrorStr:@"Error de código de verificación"];
        
    }];
}

@end
